package StudyCode.summary.zipfile;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ExtractZipFileToOutDir {
	public static boolean extract(File zipfile, File outputDirectory) {
		boolean isSuccessful = false;
		try {
			isSuccessful = extract(new FileInputStream(zipfile),
					outputDirectory);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return isSuccessful;
	}

	public static boolean extract(InputStream zipfile, File outputDirectory) {
		boolean isSuccessful = false;
		try {
			ZipInputStream zin = new ZipInputStream(zipfile);
			ZipEntry entry;
			String name, dir;
			while ((entry = zin.getNextEntry()) != null) {
				name = entry.getName();
				if (entry.isDirectory()) {
					mkdirs(outputDirectory, name);
					continue;
				}

				dir = dirpart(name);
				if (dir != null) {
					mkdirs(outputDirectory, dir);
				}
				extractFile(zin, outputDirectory, name);
			}
			zin.close();
			isSuccessful = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return isSuccessful;
	}

	private static void mkdirs(File outputDirectory, String path) {
		File d = new File(outputDirectory, path);
		if (!d.exists()) {
			d.mkdirs();
		}
	}

	private static String dirpart(String name) {
		int s = name.lastIndexOf(File.separatorChar);
		return s == -1 ? null : name.substring(0, s);
	}

	private static void extractFile(ZipInputStream in,
	                                File outputDirectory, String name) throws IOException {
		final int BUFFER_SIZE = 1024;
		byte[] buffer = new byte[BUFFER_SIZE];
		BufferedOutputStream out = new BufferedOutputStream(
				new FileOutputStream(new File(outputDirectory, name)));
		int count;
		while ((count = in.read(buffer)) != -1) {
			out.write(buffer, 0, count);
		}
		out.close();
	}
}
